import re
import time
import requests
import json
from github import Github
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.tmt.v20180321 import tmt_client, models

tencent_translate_AppId = # 在这里输入腾讯翻译AppId
tencent_secret_id = # 在这里输入腾讯翻译secret_id
tencent_secret_key = # 在这里输入腾讯翻译secret_key


class MultiFunc:
    # 翻译功能
    @staticmethod
    def translate(original: str, convert: str = 'en'):
        try:
            cred = credential.Credential(tencent_secret_id, tencent_secret_key)
            client = tmt_client.TmtClient(cred, "ap-guangzhou")
            req = models.TextTranslateRequest()
            params = {
                "SourceText": original,
                "Source": "auto",
                "Target": convert,
                "ProjectId": tencent_translate_AppId
            }
            req.from_json_string(json.dumps(params))
            resp = client.TextTranslate(req)
            return resp.TargetText
        except TencentCloudSDKException as err:
            print(err)

    # 上传图片到图床功能
    @staticmethod
    def uploadImage(imgMsg):
        cmt = '来自QQ'
        timestamp = time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime())
        p = re.compile(r'=(https.+?)]')
        imgUrl = p.findall(imgMsg)
        response = requests.get(url=imgUrl[0])
        token = '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'
        g = Github(token)
        # user = g.get_user()
        # repo = user.create_repo("q_img")
        # 如果是已经存在的仓库，可以使用get_repo来获得repo对象
        repo = g.get_repo('175603a/q_img')
        # 读取文件并上传
        data = response.content
        # 不需要进行Base64编码，编码过程在create_file内部已经完成了
        try:
            repo.create_file(f'{timestamp}.jfif', f'{cmt}', data)
            res = 'https://github.com/175603a/q_img/blob/main/' + f'{timestamp}.jfif?raw=true'
        except:
            repo.create_file(f'{timestamp}.jfif', f'{cmt}', data)
            res = 'https://github.com/175603a/q_img/blob/main/' + f'{timestamp}.jfif?raw=true'
        return res

    # 图片OCR并返回结果
    @staticmethod
    def imageOCR(imgMsg):
        p = re.compile(r'=(.+?.image)')
        imgId = p.findall(imgMsg)
        url = 'http://127.0.0.1:5700/ocr_image'
        data = {
            'image': imgId
        }
        r = requests.post(url=url, data=data)
        content = ''
        for text in json.loads(r.content)['data']['texts']:
            content += text['text'] + '\n'
        return content

    # 监控日志
    @staticmethod
    def monitor_crawler():
        with open('/root/QQBot/go-cqhttp/nohup.out', 'a', encoding='utf-8') as fp:
            res = fp.read()
            fp.write('')
        return res
